<template>
  <div class="tms-ag-grid">
    <!-- table表格 -->
    <ag-grid-vue
      :style="{ width: '100%', height: height + 'px' }"
      :class="{
        'ag-theme-balham': true,
        'tms-ag-group': isGroup,
        'tms-highlight-current-row': highlightCurrentRow,
      }"
      v-bind="$attrs"
      :animateRows="true"
      :gridOptions="gridOptions"
      :localeText="localeText"
      :columnDefs="columns"
      :rowData="data || []"
      :rowSelection="rowSelection"
      :rowDragManaged="rowDragManaged"
      :suppressRowClickSelection="hasCheck"
      :rowHeight="30"
      :headerHeight="tmsShowFilter ? 30 : 45"
      :floatingFiltersHeight="45"
      :frameworkComponents="frameworkComponents"
      :singleClickEdit="true"
      @cell-clicked="onCellClicked"
      @cell-double-clicked="onCellDoubleClicked"
      @row-clicked="onRowClicked"
      @cell-editing-stopped="onCellEditingStopped"
      @row-editing-stopped="onRowEditingStopped"
      @row-drag-end="onRowDragEnd"
      @row-double-clicked="onRowDoubleClicked"
      @row-selected="select"
      @selection-changed="selectionChange"
      @row-value-changed="currentChange"
      @sort-changed="sortChangeHandler"
      @filter-changed="filterChangeHandler"
      @grid-ready="onGridReady"
      @gridSizeChanged="tmsColumnsFit"
      @row-data-changed="tmsColumnsFit"
      @grid-columns-changed="tmsColumnsFit"
    >
    </ag-grid-vue>
    <!-- 设置 -->
    <section class="table-setting" @click="tableSetting" v-if="tableSettingBtn">
      <i class="el-icon-setting"></i>
    </section>
    <div v-if="searchBox == true" class="search_btn">
      <i @click="findData($event)" class="el-icon-search"></i>
      <i @click="delSearchData($event)" class="el-icon-delete"></i>
    </div>
    <!-- 分页 -->
    <div v-if="pageDetail" class="pagination-container page">
      <div
        class="pageCon"
        :style="{ border: pageDetail ? '1px solid #e0e6ed' : '0px' }"
      >
        <template v-if="pageDetail">
          {{$t('app.page',{page,pageSize,total,num:Math.ceil(total / pageSize)})}}
        </template>
      </div>
      <div class="block">
        <el-pagination
          layout="total, sizes, prev, pager, next"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <div class="clearfix"></div>

    <!-- table设置弹窗 -->
    <el-dialog
      :title="$t('other.customtable')"
      v-dialogDrag
      :visible.sync="showTableSetting"
      width="900px"
      class="tms-setting-dialog"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-tabs v-model="settingTab">
        <el-tab-pane :label="$t('other.tableshowconfig')" name="first">
          <section class="left-table">
            <div class="setting-title">
              {{ $t('other.hidefield')}}（{{ hideColumns.length }}）
            </div>
            <el-table
              border
              fit
              highlight-current-row
              stripe
              :data="hideColumns"
              height="330px"
              @selection-change="leftSelectionChange"
            >
              <el-table-column
                class-name="tms-index-column"
                align="center"
                fixed
                type="selection"
                width="50"
              ></el-table-column>
              <el-table-column
                align="center"
                minWidth="150"
                prop="name"
                :label="$t('other.fieldname')"
                :show-overflow-tooltip="true"
              >
              </el-table-column>
              <el-table-column
                align="center"
                minWidth="100"
                prop="width"
                :label="$t('other.fieldwidth') + '(PX)'"
                :show-overflow-tooltip="true"
              >
              </el-table-column>
            </el-table>
          </section>
          <section class="middle-action">
            <section class="action-main">
              <el-button
                type="primary"
                plain
                icon="el-icon-arrow-right"
                circle
                @click="moveRight"
              >
              </el-button>
              <el-button
                type="primary"
                plain
                icon="el-icon-arrow-left"
                circle
                @click="moveLeft"
              >
              </el-button>
            </section>
          </section>
          <section class="right-table right-table-setting ui-right-table">
            <div class="setting-title">
              {{ $t('other.showfield') }}（{{ showColumns.length }}）
            </div>
            <el-table
              border
              fit
              highlight-current-row
              stripe
              row-key="field"
              :data="showColumns"
              height="330px"
              @selection-change="rightSelectionChange"
            >
              <el-table-column
                class-name="tms-index-column"
                align="center"
                type="selection"
                width="50"
              >
              </el-table-column>
              <el-table-column
                minWidth="150"
                prop="name"
                :label="$t('other.fieldname')"
                :show-overflow-tooltip="true"
                align="center"
              >
              </el-table-column>
              <el-table-column
                class-name="width-edit-column"
                align="center"
                minWidth="100"
                prop="width"
                :label="$t('other.fieldwidth') + '(PX)'"
                :show-overflow-tooltip="true"
              >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.width"></el-input>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                class-name="drag-action-column"
                minWidth="70"
                prop="action"
                :label="$t('other.drag')"
              >
                <template slot-scope="scope">
                  <i class="el-icon-rank"></i>
                  <span style="display:none;">{{ scope.rows }}</span>
                </template>
              </el-table-column>
            </el-table>
          </section>
        </el-tab-pane>
        <el-tab-pane :label="$t('other.tableexportconfig')" name="second">
          <section class="left-table">
            <div class="setting-title">
              {{ $t('other.hidefield')}}（{{ hideExportColumns.length }}）
            </div>
            <el-table
              border
              fit
              highlight-current-row
              stripe
              :data="hideExportColumns"
              height="330px"
              @selection-change="leftExportSelectionChange"
            >
              <el-table-column
                class-name="tms-index-column"
                align="center"
                fixed
                type="selection"
                width="50"
              ></el-table-column>
              <el-table-column
                align="center"
                minWidth="150"
                prop="name"
                :label="$t('other.fieldname')"
                :show-overflow-tooltip="true"
              >
              </el-table-column>
              <el-table-column
                align="center"
                minWidth="100"
                prop="width"
                :label="$t('other.fieldwidth') + '(PX)'"
                :show-overflow-tooltip="true"
              >
              </el-table-column>
            </el-table>
          </section>
          <section class="middle-action">
            <section class="action-main">
              <el-button
                type="primary"
                plain
                icon="el-icon-arrow-right"
                circle
                @click="moveExportRight"
              >
              </el-button>
              <el-button
                type="primary"
                plain
                icon="el-icon-arrow-left"
                circle
                @click="moveExportLeft"
              >
              </el-button>
            </section>
          </section>
          <section class="right-table right-export-table">
            <div class="setting-title">
              {{ $t('other.showfield') }}（{{ showExportColumns.length }}）
            </div>
            <el-table
              border
              fit
              highlight-current-row
              stripe
              row-key="field"
              :data="showExportColumns"
              height="330px"
              @selection-change="rightExportSelectionChange"
            >
              <el-table-column
                class-name="tms-index-column"
                align="center"
                type="selection"
                width="50"
              >
              </el-table-column>
              <el-table-column
                minWidth="150"
                prop="name"
                :label="$t('other.fieldname')"
                :show-overflow-tooltip="true"
                align="center"
              >
              </el-table-column>
              <el-table-column
                class-name="width-edit-column"
                align="center"
                minWidth="100"
                prop="width"
                :label="$t('other.fieldwidth') + '(PX)'"
                :show-overflow-tooltip="true"
              >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.width"></el-input>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                class-name="drag-action-column"
                minWidth="70"
                prop="action"
                :label="$t('other.drag')"
              >
                <template slot-scope="scope">
                  <i class="el-icon-rank"></i>
                  <span style="display:none;">{{ scope.rows }}</span>
                </template>
              </el-table-column>
            </el-table>
          </section>
        </el-tab-pane>
      </el-tabs>
      <section slot="footer" class="dialog-footer">
        <el-button
          plain
          type="primary"
          @click="applySetting"
          :loading="tableSetLoading"
          :disabled="tableSetLoading"
          >{{ $t('other.apply') }}
        </el-button>
        <el-button
          plain
          @click="resetSetting"
          :loading="tableSetLoading"
          :disabled="tableSetLoading"
          >{{ $t('other.reset') }}</el-button
        >
        <el-button
          plain
          @click="showTableSetting = false"
          >{{ $t('other.cancel') }}</el-button
        >
      </section>
    </el-dialog>
  </div>
</template>
<script>
import Sortable from "sortablejs";
// import { selectByModuleIdAndDefineId, editColumnDefine, restoreDefaultColumnDefine } from '@/api/system/system'
import { getColumnConfig } from "@/api/system/table";
import { AgGridVue } from "ag-grid-vue";
import CustomHeader from ".//CustomHeader";
import DateFloatingFilter from "./DateFloatingFilter";
import AutoFilterSelectEditor from "./AutoFilterSelectEditor";
import DateEditor from "./DateEditor";
import EditRenderer from "./EditRenderer";
import InputEditor from "./InputEditor";
import SelectEditor from "./SelectEditor";
import SwitchEditor from "./SwitchEditor";
import gridDefaultColumns from "@/assets/js/gridDefaultColumns";
import ActionRender from "./ActionRender.vue";
import CellRender from "./CellRender.vue";

export default {
  name: "tmsAgGrid",
  props: {
    tableSettingBtn:{
      type:Boolean,
      default:false
    },
    //表格数据
    data: {
      type: Array,
      default: function() {
        return [];
      },
    },
    //表格数据请求地址
    api: {
      type: String,
    },
    //表格数据请求参数
    apiParams: {
      type: Object,
      default: () => {},
    },
    ////表格数据请求方式post/get
    apiMethod: {
      type: String,
      default: "post",
    },
    //配置列表参数menu_list_code：列表code，menu_code：菜单code
    columnConfig:{
      type:Object,
      default:() => {}
    },
    defaultColDef: {
      type: Object,
      default: function() {
        return {};
      },
    },
    columnSource: {
      type: Array,
      default: function() {
        return [];
      },
    },
    extraColumns: {
      type: Array,
      default: function() {
        return [];
      },
    },
    //行的 className 的回调方法
    rowClassName: {
      type: Function,
      default: null,
    },
    //单元格的 className 的回调方法
    cellClassName: {
      type: Function,
      default: null,
    },
    //当前行是否高亮
    highlightCurrentRow: {
      type: Boolean,
      default: false,
    },
    //是否显示复选框
    hasCheck: {
      type: Boolean,
      default: false,
    },
    //是否显示序号
    hasIndex: {
      type: Boolean,
      default: false,
    },
    //是否显示编辑图标
    hasEdit: {
      type: Boolean,
      default: false,
    },
    //是否在表格最后增加操作列
    hasAction: {
      type: Boolean,
      default: false,
    },
    //拖拽图标时是否默认拖动行
    rowDragManaged: {
      type: Boolean,
      default: false,
    },
    //是否显示删除条件查询和条件查询按钮
    searchBox: {
      type: Boolean,
      default: true,
    },
    //是否在表尾显示合计行
    showSummary: {
      type: Boolean,
      default: false,
    },
    //是否显示筛选行
    tmsShowFilter: {
      type: Boolean,
      default: false,
    },
    //是否为远程搜索
    remoteFilter: {
      type: Boolean,
      default: false,
    },
    // summary合计行位置
    summaryPosition: {
      type: String,
      default: "bottom",
    },
    //自定义的合计计算方法(tms-table)
    summaryMethod: {
      type: Function,
      default: null,
    },
    //自定义的合计计算方法(ag-grid)
    summaryMethodAgGrid: {
      type: Function,
      default: null,
    },
    //行单击事件
    rowClick: {
      type: Function,
      default: function() {},
    },
    //行双击事件
    rowdblClick: {
      type: Function,
      default: function() {},
    },
    //行拖拽事件
    rowDragEnd: {
      type: Function,
      default: function() {},
    },
    //表格的高度
    height: {
      type: Number,
      default: 150,
    },
    //是否分页
    pageDetail: {
      type: Boolean,
      default: true,
    },
    pagination: {
      type: Boolean,
      default: false,
    },
    //表格数据总条数
    total: {
      type: Number,
      default: 0,
    },
    //当前页数
    page: {
      type: Number,
      default: 1,
    },
    //每页显示几条数据
    pageSize: {
      type: Number,
      default: function() {
        return this.PAGESIZE;
      },
    },
    pageSizes: {
      type: Array,
      default: function() {
        return this.PAGESIZES;
      },
    },
  },
  data() {
    return {
      tableLoading: false,
      showTableSetting: false,
      gridObj: {},
      gridOptions: {
        getRowClass: this.rowClass,
        enableCellTextSelection: true,
        defaultColDef:{
          lockPosition:true
        }
      },
      localeText: {
        noRowsToShow: this.$t('other.none'),
      },
      frameworkComponents: {
        dateFloatingFilter: DateFloatingFilter,
        autoFilterSelectEditor: AutoFilterSelectEditor,
        dateEditor: DateEditor,
        editRenderer: EditRenderer,
        inputEditor: InputEditor,
        selectEditor: SelectEditor,
        switchEditor: SwitchEditor,
      },
      rowSelection: "multiple",
      resizedColsMap: {},
      curSumObj: {}, //当前页合计行
      curTotal: 0, //当前页行数
      columns: [], //表格最终显示的列
      allColumns: [], //系统默认配置的列
      showColumns: [], //用户自定义表格配置的列
      hideColumns: [],
      leftMultipleSelection: [], //表格配置左侧表格选中数据
      rightMultipleSelection: [], //表格配置右侧表格选中数据
      defaultSettingObj: {}, //系统默认模块表格配置对象
      userSettingObj: {}, //用户自定义模块表格配置对象
      settingTab: "first",
      //导出配置
      showExportColumns: [], //用户自定义导出配置的列
      hideExportColumns: [],
      leftExportMultipleSelection: [], //导出配置左侧表格选中数据
      rightExportMultipleSelection: [], //导出配置右侧表格选中数据
      defaultExportSettingObj: {}, //系统默认模块导出配置对象
      userExportSettingObj: {}, //用户自定义模块导出配置对象
      tableSetLoading:false
    };
  },
  computed: {
    isGroup() {
      return this.columns.some((obj) => !this.isResultEmpty(obj.children));
    },
  },
  components: {
    AgGridVue,
    ActionRender,
    CustomHeader,
    DateFloatingFilter,
    AutoFilterSelectEditor,
    DateEditor,
    EditRenderer,
    InputEditor,
    SelectEditor,
    SwitchEditor,
    CellRender
  },
  created() {
    this.initSetting();
  },
  beforeMount() {
    this.gridOptions.context = {
      componentParent: this,
    };
    window.addEventListener("resize", () => {
      this.$emit("update:height", this.getHeight(window, 360));
      this.gridObj.api && this.gridObj.api.doLayout();
    });
  },
  methods: {
    //初始化设置
    initSetting() {
      if (this.columnSource && this.columnSource.length > 0) {
        let tmpColumns = this._.cloneDeep(this.columnSource);
        let extraColumn = this._.cloneDeep(this.extraColumns);
        extraColumn = extraColumn.map((obj) => {
          return this.elTableToAgGrid(obj, false, true);
        });
        tmpColumns = tmpColumns.map((obj, index) => {
          obj = this.elTableToAgGrid(obj);
          // if (index == 0) {
          //   obj.fixed = "left";
          //   obj.pinned = "left";
          // }
          let extra = extraColumn.filter((col) => {
            return col.field == obj.field;
          });
          obj = Object.assign(obj, extra[0]);
          return obj;
        });
        this.columns = [];
        if (this.hasCheck) {
          //选择列
          let checkCloumn = {
            headerName: "",
            field: "selection",
            checkboxSelection: true,
            headerCheckboxSelection: true,
            headerCheckboxSelectionFilteredOnly: true,
            minWidth: 30,
            width: 30,
            pinned: "left",
            cellClass: "tms-cell-index-select",
            headerClass: "tms-no-children-header",
          };
          this.columns.push(checkCloumn);
        }
        if (this.hasEdit) {
          //编辑列
          let checkCloumn = {
            headerName: "",
            field: "edit",
            minWidth: 30,
            width: 30,
            pinned: "left",
            cellClass: "tms-cell-index-edit el-icon-edit",
            headerClass: "tms-no-children-header",
          };
          this.columns.push(checkCloumn);
        }
        if (this.hasIndex) {
          //序号列
          let _self = this;
          let indexCloumn = {
            headerName: this.$t('app.index'),
            field: "index",
            minWidth: 60,
            width: 60,
            pinned: "left",
            cellStyle: {
              "text-align": "center",
            },
            cellRenderer: _self.indexFormat,
            cellClass: "tms-cell-index-select",
            headerClass: "tms-no-children-header",
          };
          this.columns.push(indexCloumn);
        }
        this.columns = this.columns.concat(tmpColumns);
        this.allColumns = tmpColumns;
        this.showExportColumns = Object.assign([], tmpColumns);
      } else {
        this.tableLoading = true;
        const {menu_list_code,menu_id} = this.columnConfig;
        if ( menu_list_code === "gridColumnsInfo" && menu_id === "gridColumnsInfo" ) {
          this.columns = this.columns.concat(gridDefaultColumns.info);
          this.initAfter();
          return;
        }
        if ( menu_list_code === "gridColumnsSort" && menu_id === "gridColumnsSort" ) {
          this.columns = this.columns.concat(gridDefaultColumns.sort);
          this.initAfter();
          return;
        }
        if ( menu_list_code === "tableConfigList" && menu_id === "tableConfigList" ) {
          this.columns = this.columns.concat(
            gridDefaultColumns.tableConfigList
          );
          this.initAfter();
          return;
        }
        this.getColumnConfig();
      }
    },
    getColumnConfig() {
      //获取表格配置项
      getColumnConfig(this.columnConfig)
        .then((res) => {
            this.hideColumns = res.data.tableHiding || [];
            this.showColumns = res.data.tableDisplay || [];
            this.hideExportColumns = res.data.exportHidden || [];
            this.showExportColumns = res.data.exportDisplay || [];
            let arr = res.data.tableDisplay || [];
            arr.concat(this.extraColumns);
            arr.forEach((item) => {
              item = this.columnChange(item);
            });
            // arr.sort(function(a, b) {
            //   return a.sort_num > b.sort_num ? 1 : -1;
            // });
            this.columns = [];
            if (this.hasCheck) {
              //选择列
              let checkCloumn = {
                name: "",
                field: "selection",
                checkboxSelection: true,
                headerCheckboxSelection: true,
                headerCheckboxSelectionFilteredOnly: true,
                maxWidth: 30,
                width: 30,
                pinned: "left",
              };
              this.columns.push(checkCloumn);
            }
            if (this.hasEdit) {
              //编辑列
              let checkCloumn = {
                headerName: "",
                field: "edit",
                maxWidth: 30,
                width: 30,
                pinned: "left",
                cellClass: "base-cell-index-edit el-icon-edit",
                headerClass: "tms-no-children-header",
              };
              this.columns.push(checkCloumn);
            }
            if (this.hasIndex) {
              //序号列
              let indexCloumn = {
                headerName: this.$t('app.index'),
                field: "index",
                maxWidth: 60,
                width: 60,
                pinned: "left",
                cellStyle: {
                  "text-align": "center",
                },
                cellRenderer: _self.indexFormat,
                cellClass: "tms-cell-index-select",
                headerClass: "tms-no-children-header",
              };
              this.columns.push(indexCloumn);
            }
            this.allColumns = arr;
            this.columns = this.columns.concat(arr);
            this.$nextTick(() => {
              this.tableLoading = false;
            });
          
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    initAfter() {
      const columns = this._.cloneDeep(this.columns);
      columns.forEach((column) => {
        column.name = this.$t(column.name);
        if ( column.editable && column.cellEditor == "SelectEditor" ) {
          column.valueFormatter = (params) => {
            const opts = column.cellEditorParams.list;
            return this.$t(opts.find(opt => opt.value == params.value)?.label)||params.value;
          }
        }
        column = this.columnChange(column)
      });
      this.columns = columns;
    },
    /**
     * 操作数据列（新增/删除）
     * 参数：index新增列下标，size新增多少项
     * */
    actionEvent(index, type) {
      this.$emit("action", index, type);
    },
    /**
     * el-table列配置项转换为ag-grid列配置项
     * 参数：elColumn：el-table的列配置
     * 返回：ag-grid的列配置
     */
    elTableToAgGrid(elColumn, hasChildren, isExtra) {
      let agColumn = this._.cloneDeep(elColumn);
      agColumn.resizable = false;
      agColumn.sortable = true;
      agColumn.floatingFilter = this.tmsShowFilter;
      if (elColumn.label) {
        agColumn.headerName = this._cw(elColumn.label);
      }
      if (elColumn.prop) {
        agColumn.field = elColumn.prop;
      }
      if (!isExtra) {
        if (
          this.isFieldEmpty(agColumn.minWidth) ||
          Number(agColumn.minWidth) === 0
        ) {
          agColumn.minWidth = 100;
        }
      }
      if (elColumn.tmsFilterType) {
        if (elColumn.tmsFilterType == "date") {
          agColumn.filter = "agDateColumnFilter";
          agColumn.filterParams = {
            comparator: this.filterComparator,
            inRangeInclusive: true,
          };
          agColumn.floatingFilterComponent = "dateFloatingFilter";
        } else if (elColumn.tmsFilterType == "number") {
          agColumn.filter = "agNumberColumnFilter";
          agColumn.cellStyle = {
            "text-align": "right",
          };
        } else {
          agColumn.filter = "agTextColumnFilter";
          agColumn.comparator = (valueA, valueB) => {
            let tmpA = valueA || "";
            let tmpB = valueB || "";
            return tmpA.toString().localeCompare(tmpB.toString());
          };
        }
      }
      if (elColumn.fixed === true || elColumn.fixed === "left") {
        agColumn.pinned = "left";
      } else if (elColumn.fixed === "right") {
        agColumn.pinned = "right";
      }
      if (elColumn.formatter && typeof elColumn.formatter === "function") {
        agColumn.cellRenderer = (params) => {
          if (params.data.tmsSummary === true) {
            // 合计行
            return params.value;
          } else {
            let row = params.data;
            let column = this.agGridToElTable(params.colDef);
            let cellValue = params.value;
            return (
              '<span class="tms-table-span">' +
              (elColumn.formatter.call(null, row, column, cellValue) || "") +
              "</span>"
            );
          }
        };
      } else if (elColumn.tmsFilterType == "date") {
        agColumn.cellRenderer = (params) => {
          if (params.data.tmsSummary === true) {
            // 合计行
            return params.value;
          } else {
            return (
              '<span class="tms-table-span">' +
              (this.agGridTimeFormatter(params) || "") +
              "</span>"
            );
          }
        };
      } else {
        agColumn.cellRenderer = (params) => {
          if (params.data.tmsSummary === true) {
            // 合计行
            return params.value;
          } else {
            return (
              '<span class="tms-table-span">' + (params.value || "") + "</span>"
            );
          }
        };
      }
      if (agColumn.field == "index" || agColumn.field == "selection") {
        agColumn.cellClass = "tms-cell-index-select";
      } else {
        agColumn.cellClass = this.cellClass;
      }
      if (elColumn.children && !this.isResultEmpty(elColumn.children)) {
        agColumn.children = elColumn.children.map((obj) => {
          return this.elTableToAgGrid(obj, true);
        });
      }
      if (hasChildren) {
        agColumn.headerClass = "tms-has-children-header";
      } else {
        agColumn.headerClass = "tms-no-children-header";
      }
      return agColumn;
    },
    /**
     * ag-grid列配置项转换为el-table列配置项
     * 参数：ag-grid的列配置
     * 返回：elColumn：el-table的列配置
     */
    agGridToElTable(agColumn) {
      let elColumn = this._.cloneDeep(agColumn);
      if (elColumn.field === "index" || elColumn.field === "selection") {
        elColumn.type = elColumn.field;
      }
      elColumn.property = elColumn.field;
      elColumn.label = elColumn.headerName;
      if (elColumn.filter == "agDateColumnFilter") {
        elColumn.tmsFilterType = "date";
      } else if (elColumn.filter == "agNumberColumnFilter") {
        elColumn.tmsFilterType = "number";
      } else {
        elColumn.tmsFilterType = "string";
      }
      if (elColumn.children && !this.isResultEmpty(elColumn.children)) {
        elColumn.children = elColumn.children.map((obj) => {
          return this.agGridToElTable(obj);
        });
      }
      return elColumn;
    },
    /**
     * 后台传输字段转化为agGrid需要的字段
     */
    columnChange(column) {
      column.field = column.code;
      column.headerName = column.name;
      column.dateType =
        column.type === "10403"
          ? "datetime"
          : column.type === "10402"
          ? "string"
          : column.type === "10401"
          ? "number"
          : "";
      if (column.issearch === "0") {
        column.filter = false;
      }
      if (column.issearch === "1" && column.dateType === "string") {
        column.floatingFilter = true;
        column.filter = "agTextColumnFilter";
      }
      if (
        column.issearch === "1" &&
        (column.dateType === "date" || column.dateType === "datetime")
      ) {
        column.floatingFilter = true;
        column.filter = "agDateColumnFilter";
      }
      if (column.issearch === "1" && column.dateType === "number") {
        column.floatingFilter = true;
        column.filter = "agNumberColumnFilter";
      }
      if (column.issearch === "1" && column.dateType === "select") {
        column.floatingFilter = true;
        column.filter = "agNumberColumnFilter";
      }
      column.width = column.width ? parseInt(column.width) : 100;
      column.minWidth = column.width ? parseInt(column.width) : 100;
      return column;
    },
    /*
     * 表格配置数据格式化
     * 参数：defaultSetting——系统默认配置
     *       userSetting——用户自定义配置
     *       extraColumn——需要进行额外配置的列
     * 返回：{
     *          allColumns——默认列
     *          userColumns——用户自定义列
     *       }
     */
    tableHeadSetting(defaultSetting, userSetting, extraColumn) {
      //默认所有列配置格式化
      let allColumns = JSON.parse(defaultSetting.dataListConfig);
      allColumns = allColumns.map((obj, index) => {
        if (obj.children && !this.isResultEmpty(obj.children)) {
          obj.children = obj.children.map((child) => {
            let childExtra = extraColumn.filter((childCol) => {
              return childCol.prop == child.prop;
            });
            child = Object.assign(child, childExtra[0]);
            return child;
          });
        }
        let extra = extraColumn.filter((col) => {
          return col.prop == obj.prop;
        });
        obj = Object.assign(obj, extra[0]);
        return obj;
      });
      //用户自定义列配置格式化
      let userColumns = JSON.parse(userSetting.dataListConfig);
      userColumns = userColumns.map((obj, index) => {
        if (obj.children && !this.isResultEmpty(obj.children)) {
          obj.children = obj.children.map((child) => {
            let childExtra = extraColumn.filter((childCol) => {
              return childCol.prop == child.prop;
            });
            child = Object.assign(child, childExtra[0]);
            return child;
          });
        }
        let extra = extraColumn.filter((col) => {
          return col.prop == obj.prop;
        });
        obj = Object.assign(obj, extra[0]);
        obj = this.elTableToAgGrid(obj);
        return obj;
      });
      return {
        allColumns: allColumns,
        userColumns: userColumns,
      };
    },
    rowClass(params) {
      let obj = {
        row: params.data,
        rowIndex: params.rowIndex,
      };
      if (typeof this.rowClassName === "string") {
        return this.rowClassName;
      } else if (typeof this.rowClassName === "function") {
        if (params.data.tmsSummary) {
          return "";
        } else {
          return this.rowClassName.call(null, obj);
        }
      } else {
        return "";
      }
    },
    cellClass(params) {
      // 列序号
      let fields = this.columns.map((obj) => {
        return obj.field;
      });
      let columnIndex = fields.indexOf(params.colDef.field);
      if (
        typeof this.cellClassName === "string" ||
        Array.isArray(this.cellClassName)
      ) {
        return this.cellClassName;
      } else if (typeof this.cellClassName === "function") {
        if (params.data.tmsSummary) {
          return "";
        } else {
          return this.cellClassName.call(null, {
            rowIndex: params.rowIndex,
            columnIndex: columnIndex,
            row: params.data,
            column: this.agGridToElTable(params.colDef),
          });
        }
      } else {
        return "";
      }
    },
    // 当前页合计行
    curPageSummary(data) {
      if (this.showSummary) {
        let curColumns = this.deepClone(this.columns),
          curData = this.deepClone(data);
        curColumns.forEach((obj, index) => {
          if (index === 0) {
            this.curSumObj[obj.field] = "当前页";
            return;
          }
          if (obj.children && obj.children.length > 0) {
            let childColumns = this.deepClone(obj.children);
            childColumns.forEach((childObj, childIndex) => {
              const childValues = curData.map((item) =>
                Number(item[childObj.field])
              );
              if (childObj.tmsFilterType === "number") {
                this.curSumObj[childObj.field] = childValues.reduce(
                  (prev, curr) => {
                    const childValue = Number(curr);
                    if (!isNaN(childValue)) {
                      return prev + curr;
                    } else {
                      return prev;
                    }
                  },
                  0
                );
                this.curSumObj[childObj.field] =
                  Math.round(this.curSumObj[childObj.field] * 100) / 100;
              } else {
                this.curSumObj[childObj.field] = "";
              }
            });
          } else if (obj.tmsFilterType === "number") {
            const values = curData.map((item) => Number(item[obj.field]));
            this.curSumObj[obj.field] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            this.curSumObj[obj.field] =
              Math.round(this.curSumObj[obj.field] * 100) / 100;
          } else {
            this.curSumObj[obj.field] = "";
          }
        });
        this.curTotal = curData.length || 0;
      }
    },
    summaryMethodHandler() {
      // 合计行
      if (this.showSummary) {
        let sum = [{}];
        if (
          this.summaryMethodAgGrid &&
          this.summaryMethodAgGrid != null &&
          typeof this.summaryMethodAgGrid == "function"
        ) {
          sum = this.summaryMethodAgGrid.call(null);
        } else if (
          this.summaryMethod &&
          this.summaryMethod != null &&
          typeof this.summaryMethod == "function"
        ) {
          let obj = {
            columns: this.columns.map((obj) => {
              return this.agGridToElTable(obj);
            }),
            data: this.data,
          };
          let tmpSum = this.summaryMethod.call(null, obj);
          let sumObj = {};
          this.columns.map((obj, index) => {
            sumObj[obj.field] = tmpSum[index];
          });
          sum = [sumObj];
        } else {
          sum = [{}];
        }
        sum[0].index = "总合计";
        let totalSumObj = this.deepClone(sum[0]);
        for (let tmpKey in totalSumObj) {
          let tmpValue = totalSumObj[tmpKey];
          if (typeof tmpValue === "string" && tmpValue.indexOf("共 ") === 0) {
            let tmpArr = tmpValue.split(" ");
            if (tmpArr.length === 3) {
              this.curSumObj[tmpKey] =
                tmpArr[0] + " " + this.curTotal + " " + tmpArr[2];
            }
          }
        }
        sum.unshift(this.curSumObj);
        sum = sum.map((obj) => {
          obj.tmsSummary = true;
          return obj;
        });
        if (this.summaryPosition === "bottom") {
          this.gridObj.api && this.gridObj.api.setPinnedBottomRowData(sum);
        } else if (this.summaryPosition === "top") {
          this.gridObj.api && this.gridObj.api.setPinnedTopRowData(sum);
        }
      }
    },
    //每页条数change
    handleSizeChange(size) {
      this.$emit("size-change", size);
    },
    //当前页数change
    handleCurrentChange(currentPage) {
      this.$emit("current-change", currentPage);
    },
    //当用户手动勾选数据行的 Checkbox 时触发的事件
    select(event) {
      let selection = event.api.getSelectedRows();
      this.$emit("select", selection, event.data);
      if (!this.hasCheck) {
        this.currentChange(event);
      }
    },
    //当选择项发生变化时会触发该事件
    selectionChange(event) {
      let selection = event.api.getSelectedRows();
      this.$emit("selection-change", selection);
    },
    //用于多选表格，清空用户的选择
    clearSelection() {
      this.gridObj.api && this.gridObj.api.deselectAll();
    },
    //切换某一行的选中状态
    toggleRowSelection(row, selected) {
      let _self = this;
      this.gridObj.api.forEachNode(function(node) {
        console.log("1111");
        if (_self.isObjEqual(node.data, row)) {
          node.setSelected(selected);
        }
      });
    },
    // 用于单选表格，设定某一行为选中行，如果调用时不加参数，则会取消目前高亮行的选中状态
    setCurrentRow(row) {
      this.clearSelection();
      let _self = this;
      if (!_self.hasCheck) {
        _self.gridObj.api.forEachNode(function(node) {
          if (_self.isObjEqual(node.data, row)) {
            node.setSelected(true);
          }
        });
      }
    },
    //当表格的当前行发生变化的时候会触发该事件
    currentChange(event) {
      this.$emit("table-current-change", event.data, {});
    },
    //index序号格式化
    indexFormat(params) {
      if (params.data.tmsSummary === true) {
        return params.value;
      } else {
        if (this.pageDetail) {
          return (this.page - 1) * this.pageSize + (params.rowIndex + 1);
        } else {
          return params.rowIndex + 1;
        }
      }
    },
    onGridReady(params) {
      this.gridObj = params;
      this.$emit("grid-ready", params);
    },
    tmsColumnsFit(params) {
      if (params.type === "gridSizeChanged" && params.clientWidth === 0) {
        return;
      }
      this.gridObj = params;
      params.api.sizeColumnsToFit();
    },
    onCellClicked(event) {
      if (
        event.colDef.editable === true ||
        this.defaultColDef.editable === true
      ) {
        return;
      }
      if (
        typeof event.colDef.cellClass === "string" &&
        event.colDef.cellClass.indexOf("el-icon-edit") != -1
      ) {
        // 这里一定是点击的编辑
        this.$emit("setdialog", event.data);
        return;
      }
      // 非空则复制到粘贴板
      // if (event.event.target.innerText !== "") {
      //   this.$copyText(event.event.target.innerText);
      // }
      if (event.event.target.className == "tms-table-span") {
        this.$emit(
          "cellClick",
          event.data,
          this.agGridToElTable(event.colDef),
          event.event.target,
          event.event
        );
      }
    },
    onCellDoubleClicked(event) {
      // 非空则复制到粘贴板
      if (event.event.target.innerText !== "") {
        this.$copyText(event.event.target.innerText);
      }
      this.$emit(
        "cell-dblclick",
        event.data,
        this.agGridToElTable(event.colDef),
        event.event.target,
        event.event
      );
    },
    onRowClicked(event) {
      this.rowClick(event.data);
    },
    onRowDoubleClicked(event) {
      this.rowdblClick(event.data);
    },
    onCellEditingStopped(event) {
      let updateData = this._.cloneDeep(this.data);
      if (
        event.colDef.cellEditor == "agSelectCellEditor" &&
        Array.isArray(event.colDef.options)
      ) {
        updateData[event.rowIndex][
          event.colDef.field
        ] = event.colDef.options.find((opt) => opt.label == event.value).value;
        this.$emit("update:data", updateData);
      }
    },
    onRowDragEnd(event) {
      var itemsToUpdate = [];
      event.api.forEachNodeAfterFilterAndSort(function(rowNode) {
        itemsToUpdate.push(rowNode.data);
      });
      this.$emit("update:data", itemsToUpdate);
      this.$emit("row-drag-end", itemsToUpdate);
    },
    onRowEditingStopped(event) {
      console.log(event);
    },
    sortChangeHandler(event) {
      event.api.refreshCells({ force: true });
      this.$emit("sort-changed", event);
    },
    filterChangeHandler(event) {
      event.api.refreshCells({ force: true });
      if (this.remoteFilter) {
        this.$emit("filter-changed", event);
      } else {
        let filteredData = [];
        event.api.forEachNodeAfterFilter((node, index) => {
          filteredData.push(node.data);
        });
        this.curPageSummary(filteredData);
        this.summaryMethodHandler();
      }
    },
    /**
     * 日期筛选框comparator
     */
    filterComparator(filterLocalDateAtMidnight, cellValue) {
      let dateAsString = this.formatDateGlobal(cellValue, "yyyy-MM-dd");
      if (dateAsString == null) return -1;
      let dateParts = dateAsString.split("-");
      let cellDate = new Date(
        Number(dateParts[0]),
        Number(dateParts[1]) - 1,
        Number(dateParts[2])
      );
      if (filterLocalDateAtMidnight.getTime() === cellDate.getTime()) {
        return 0;
      }
      if (cellDate.getTime() < filterLocalDateAtMidnight.getTime()) {
        return -1;
      }
      if (cellDate.getTime() > filterLocalDateAtMidnight.getTime()) {
        return 1;
      }
    },
    //设置
    tableSetting() {
      this.showTableSetting = true;
    },
    leftSelectionChange(selections) {
      this.leftMultipleSelection = selections;
    },
    rightSelectionChange(selections) {
      this.rightMultipleSelection = selections;
    },
    //拖拽初始化
    setSort() {
      //表格配置拖拽
      const el = document.querySelectorAll(
        ".right-table-setting .el-table__body-wrapper > table > tbody"
      )[0];
      let _self = this;
      this.sortable = Sortable.create(el, {
        ghostClass: "sortable-ghost",
        onEnd: (evt) => {
          const targetRow = _self.showColumns.splice(evt.oldIndex, 1)[0];
          _self.showColumns.splice(evt.newIndex, 0, targetRow);
        },
      });
      console.log(this.sortable, "this.sortable");
      //导出配置拖拽
      const exportEl = document.querySelectorAll(
        ".right-export-table .el-table__body-wrapper > table > tbody"
      )[0];
      this.sortExportable = Sortable.create(exportEl, {
        ghostClass: "sortable-ghost",
        onEnd: (evt) => {
          const targetExportRow = _self.showExportColumns.splice(
            evt.oldIndex,
            1
          )[0];
          _self.showExportColumns.splice(evt.newIndex, 0, targetExportRow);
        },
      });
    },
    //右移
    moveRight() {
      if (this.leftMultipleSelection.length > 0) {
        this.leftMultipleSelection.forEach((item) => {
          const index = this.hideColumns.findIndex(
            (col) => col.code == item.code
          );
          this.hideColumns.splice(index, 1);
        });
      }
      this.showColumns = this.showColumns.concat(this.leftMultipleSelection);
    },
    //左移
    moveLeft() {
      if (this.rightMultipleSelection.length > 0) {
        this.rightMultipleSelection.forEach((item) => {
          const index = this.showColumns.findIndex(
            (col) => col.code == item.code
          );
          this.showColumns.splice(index, 1);
        });
      }
      this.hideColumns = this.hideColumns.concat(this.rightMultipleSelection);
    },
    /*
     *导出设置
     */
    leftExportSelectionChange(selections) {
      this.leftExportMultipleSelection = selections;
    },
    rightExportSelectionChange(selections) {
      this.rightExportMultipleSelection = selections;
    },
    //右移
    moveExportRight() {
      if(this.leftExportMultipleSelection.length > 0){
        this.leftExportMultipleSelection.forEach(item => {
          const index = this.hideExportColumns.findIndex(col => col.code == item.code);
          this.hideExportColumns.splice(index,1)
        })
      }
      this.showExportColumns = this.showExportColumns.concat(this.leftExportMultipleSelection)
    },
    //左移
    moveExportLeft() {
      if(this.rightExportMultipleSelection.length > 0){
        this.rightExportMultipleSelection.forEach(item => {
          const index = this.showExportColumns.findIndex(col => col.code == item.code);
          this.showExportColumns.splice(index,1)
        })
      }
      this.hideExportColumns = this.hideExportColumns.concat(this.rightExportMultipleSelection)
    },
    //应用
    applySetting() {
      const {menu_list_code,menu_id} = this.columnConfig;
      let submitData = { menu_id, menu_list_code };
      this.tableSetLoading = true;
      if (this.settingTab == "first") {
        //表格配置
        const columns = this.showColumns.map((col) => {
          const { code, issearch, name, sort_num, type, width } = col;
          return { code, issearch, name, sort_num, type, width:String(width) };
        });
        submitData.data_list_config = JSON.stringify(columns);
        submitData.column_config_type = "10002";
        this.$post("/saveDisplayedOrExportedColumns", submitData)
          .then((res) => {
            this.$message.success(this.$t('msg.msg45'));
            this.showTableSetting = false;
            this.getColumnConfig();
          })
          .finally(() => {
            this.tableSetLoading = false;
          });
      } else if (this.settingTab == "second") {
        //导出配置
        const columns = this.showExportColumns.map((col) => {
          const { code, issearch, name, sort_num, type, width } = col;
          return { code, issearch, name, sort_num, type, width:String(width) };
        });
        submitData.data_list_config = JSON.stringify(columns);
        submitData.column_config_type = "10003";
        this.$post("/saveDisplayedOrExportedColumns", submitData)
          .then((res) => {
            this.$message.success(this.$t('msg.msg46'))
            this.showTableSetting = false;
            this.getColumnConfig();
          })
          .finally(() => {
            this.tableSetLoading = false;
          });
      }
    },
    //恢复默认
    resetSetting() {
      const {menu_list_code,menu_id} = this.columnConfig;
      let submitData = { menu_id, menu_list_code };
      if (this.settingTab == "first") {
        //表格配置
        submitData.column_config_type = "10002";
        this.$post("/reDefaultConfig", submitData)
          .then((res) => {
            this.$message.success(this.$t('msg.msg47'))
            this.showTableSetting = false;
            this.getColumnConfig();
          })
          .finally(() => {
            this.tableSetLoading = false;
          });
      } else if (this.settingTab == "second") {
        //导出配置
        submitData.column_config_type = "10003";
        this.$post("/reDefaultConfig", submitData)
          .then((res) => {
            this.$message.success(this.$t('msg.msg48'))
            this.showTableSetting = false;
            this.getColumnConfig();
          })
          .finally(() => {
            this.tableSetLoading = false;
          });
      }
    },
    //查询数据
    findData(e) {
      console.log("查询数据 = %o", e);
    },
    //删除查询条件
    delSearchData() {
      this.gridObj.api.setFilterModel(null);
    },
  },
  watch: {
    showTableSetting(val) {
      this.$emit("update:showTableSetting", val);
      if (val) {
        this.$nextTick(() => {
          this.setSort();
        });
      }
    },
    columnSource(val) {
      this.$emit("update:columnSource", val);
      this.initSetting();
    },
    extraColumns(val) {
      this.$emit("update:extraColumns", val);
      this.initSetting();
    },
    columns(val) {
      this.$emit("update:columns", val);
      console.log(val);
      this.showColumns = Object.assign([], val).filter((obj) => {
        return (
          obj.field !== "index" &&
          obj.field !== "selection" &&
          obj.field !== "edit"
        );
      });
      this.curPageSummary(this.data);
      this.summaryMethodHandler();
    },
    data(val) {
      this.gridObj.api.setRowData(val);
      this.curPageSummary(val);
      this.summaryMethodHandler();
    },
    height(val) {
      this.$emit("update:height", val);
      this.gridObj.api && this.gridObj.api.doLayout();
    },
    hasCheck(val) {
      if (!val) {
        this.rowSelection = "single";
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.tms-ag-grid {
  position: relative;

  &.no-edit.no-check {
    .table-setting {
      position: absolute;
      top: 13.5px;
      left: 5px;
      z-index: 100;
      width: 19px;
      height: 18px;

      .el-icon-setting {
        font-size: 18px;
      }
    }

    ::v-deep .ag-pinned-left-header {
      padding-left: 30px !important;
    }
  }

  .table-setting {
    position: absolute;
    top: 13.5px;
    left: 30px;
    z-index: 100;
    width: 19px;
    height: 18px;

    .el-icon-setting {
      font-size: 18px;
    }
  }

  .search_btn {
    position: absolute;
    top: 38px;
    left: 8px;
    z-index: 100;
  }
}
</style>
